package com.example.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.entity.Member;
import com.example.exception.CustomException;
import com.example.mapper.MemberMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Pattern;

@Service
public class MemberService {

    @Resource
    private MemberMapper memberMapper;
    private static final String EMAIL_REGEX = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
    private static final String PHONE_REGEX = "^\\d{11}$"; // 正则表达式：11位数字

    private boolean isValidPhone(String phone) {
        return Pattern.matches(PHONE_REGEX, phone);
    }

    private boolean isValidEmail(String email) {
        return Pattern.matches(EMAIL_REGEX, email);
    }

    public void add(Member member) {
        if (ObjectUtil.isEmpty(member.getPassword())) {
            member.setPassword("123456");
        }

        // 校验电话是否为11位
        if (!isValidPhone(member.getPhone())) {
            throw new CustomException("电话号码必须是11位数字");
        }

        // 校验邮箱格式
        if (!isValidEmail(member.getEmail())) {
            throw new CustomException("邮箱格式不正确");
        }

        memberMapper.insert(member);
    }

    public PageInfo<Member> selectPage(Integer pageNum, Integer pageSize, Member member) {
        PageHelper.startPage(pageNum, pageSize);
        List<Member> list = memberMapper.selectAll(member);
        return PageInfo.of(list);
    }

    public void update(Member member) {
        // 校验电话是否为11位
        if (!isValidPhone(member.getPhone())) {
            throw new CustomException("电话号码必须是11位数字");
        }

        // 校验邮箱格式
        if (!isValidEmail(member.getEmail())) {
            throw new CustomException("邮箱格式不正确");
        }

        memberMapper.updateById(member);
    }

    public void deleteById(Integer id) {
        memberMapper.deleteById(id);
    }

    public Member login(Member member) {
        Member dbMember = memberMapper.selectByUsernameAndPassword(member);
        if (ObjectUtil.isEmpty(dbMember)) {
            throw new CustomException("您输入的用户名或密码不正确");
        }
        return dbMember;
    }

    public void updatePassword(Member member) {
        // 校验一下两次密码是否一致
        if (!member.getNewPassword().equals(member.getNew2Password())) {
            throw new CustomException("两次输入的密码不一致，请重新输入");
        }
        // 把密码改成新的密码
        member.setPassword(member.getNewPassword());
        memberMapper.updateById(member);
    }
}
